package org.rk.core.common.util.encrypt;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.rk.core.common.exception.AppRuntimeException;

public class RSAFileUtil {
	public static void saveData(byte[] result, String filePath,String fileName)  {
		try {
			File f = new File(filePath);
			if (!f.exists()) {
				f.mkdirs();
			}
			FileOutputStream fosData=new FileOutputStream(filePath+fileName);
			fosData.write(result);
			fosData.close();
		} catch (Exception e) {
			throw new AppRuntimeException(e.getMessage());
		}
	}
	public static byte[] readData(String filename) {
		try {
//			String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
//			path+=filename;
			FileInputStream fisDat = new FileInputStream(filename);
		
			byte [] src=new byte [fisDat.available()];
			int len =fisDat.read(src);
			int total =0;
			while(total<src.length){
				total +=len;
				len=fisDat.read(src,total,src.length-total);
			}
			fisDat.close();
			return src;
		} catch (Exception e) {
			throw new AppRuntimeException(e.getMessage());
		}
	}
	public static void saveKey(String key,String filePath, String fileName)  {
		try {
			File f = new File(filePath);
			if (!f.exists()) {
				f.mkdirs();
			}
			String target=AESUtil.encrypt(key, "HNlWD1cjfGlmPWcJm/uFmw==");
			FileOutputStream fosData=new FileOutputStream(filePath+fileName);
			fosData.write(target.getBytes());
			fosData.close();
		} catch (Exception e) {
			throw new AppRuntimeException(e.getMessage());
		}
	}
	public static String readKey(String fileName){
		try {
			FileInputStream fisDat = new FileInputStream(fileName);
			byte [] src=new byte [fisDat.available()];
			int len =fisDat.read(src);
			int total =0;
			while(total<src.length){
				total +=len;
				len=fisDat.read(src,total,src.length-total);
			}
			fisDat.close();
			String target=AESUtil.decrypt(new String(src), "HNlWD1cjfGlmPWcJm/uFmw==");
			return new String(target);
		} catch (Exception e) {
			throw new AppRuntimeException(e.getMessage());
		}
	}
}
